import Vue from "vue";
import VueRouter from "vue-router";
import OrderManagement from "@/views/home/OrderManagement.vue";
import ProductManagement from "@/views/home/ProductManagement.vue";
import ProductDetail from "@/views/product/ProductDetail.vue"; // 导入商品详细页组件
import store from "@/store"; // 引入 Vuex store

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect:
      store.state.loginPerson || localStorage.getItem("loginPerson")
        ? "/home"
        : "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/LoginView.vue"),
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/register/RegisterView.vue"),
  },
  {
    path: "/home",
    redirect: "/store",
    component: () => import("../views/home/HomeView.vue"),
    children: [
      {
        path: "/order",
        name: "order",
        component: OrderManagement,
      },
      {
        path: "/productManagement",
        name: "product",
        component: ProductManagement,
      },
      {
        path: "/store",
        name: "store",
        component: () => import("../views/store/StoreView.vue"),
      },
      {
        path: "/cart",
        name: "cart",
        component: () => import("../views/cart/CartView.vue"),
      },
      {
        path: "/owner",
        name: "owner",
        component: () => import("../views/owner/OwnerView.vue"),
      },
      {
        path: "/product/:id", // 使用动态路由参数
        name: "productDetail",
        component: ProductDetail, // 关联商品详细页组件
      },
      {
        path: "/checkout",
        name: "Checkout",
        component: () => import("@/views/CheckoutView.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated =
    store.state.loginPerson || JSON.parse(localStorage.getItem("loginPerson"));

  // 获取用户类型
  const userType = isAuthenticated?.customer_type;

  // 白名单路由（无需登录）
  const whiteList = ["/login", "/register"];

  // 需要认证的路由
  const requiresAuth = !whiteList.includes(to.path);

  // 用户权限验证
  if (requiresAuth) {
    // 用户类型限制
    if (userType === "user" && to.path.startsWith("/productManagement")) {
      next("/home");
      return;
    }
    if (
      userType === "supplier" &&
      (to.path === "/store" || to.path === "/cart")
    ) {
      next("/productManagement");
      return;
    }
  }

  // 原有登录验证逻辑
  if (requiresAuth && !isAuthenticated) {
    next("/login");
  } else if (to.path === "/login" && isAuthenticated) {
    next(from.path);
  } else {
    next();
  }
});

export default router;
